//
//  ToolUtil.m
//  GXWN
//
//  Created by iMacOne on 15/11/5.
//  Copyright © 2015年 UNOHACHA. All rights reserved.
//

#import "ToolUtil.h"
#import <Foundation/Foundation.h>
#import <ShareSDK/ShareSDK.h>
#import <AddressBook/AddressBook.h>
#import <AddressBookUI/AddressBookUI.h>
#import <UIKit/UIKit.h>
#import <SMS_SDK/SMSSDK.h>
#import "Size.h"
#import "FileUtil.h"
#import "RootViewController.h"
#import "LeafNotification.h"
@interface ToolUtil (){
    NSInteger i;
    NSTimer *timer;
    NSTimer *promptTimer;
    UIView * view;
}
@end
@implementation ToolUtil
#pragma mark 判断字符串是否为空
+ (BOOL) isBlank:(NSString *)string {
    if (string == nil || string == NULL) {
        return YES;
    }
    string = [string stringByReplacingOccurrencesOfString:@" " withString:@""];
    if (string.length == 0) {
        return YES;
    }
    return NO;
}
+ (BOOL)isPhoneNumber:(NSString *)phoneString
{
    
    NSString *pattern = @"^1+[3578]+\\d{9}";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];
    BOOL isMatch = [pred evaluateWithObject:phoneString];
    return isMatch;
    
}
- (void)pressverify:(NSString *)number control:(UIViewController *)control button:(UIButton *)btn
{
    self.sendBtn = btn;
    if([ToolUtil isPhoneNumber: number]){
         i = 60;
        timer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(updateTimer:) userInfo:nil repeats:YES];
        [SMSSDK getVerificationCodeByMethod:SMSGetCodeMethodSMS phoneNumber:number zone:@"+86" customIdentifier:@"吾诺瀚卓" result:^(NSError *error) {
            if (!error) {
                
                NSLog(@"info %@", error.userInfo);
            }else{
                NSLog(@"aa %@",error.userInfo[@"getVerificationCode"]);
            }
            
            //           self.codeTF.text = ;
        }];
        
    }else {
        [LeafNotification showInController:control withText:@"请输入正确的手机号"];
        
    }

}
- (void)updateTimer:(NSTimer *)sender{
    
    
    [self.sendBtn setTitle:[NSString stringWithFormat:@"%ld秒",i] forState:UIControlStateNormal];
    self.sendBtn.userInteractionEnabled = NO;
    i--;
    if (i == 0) {
        self.sendBtn.userInteractionEnabled = YES;
        [timer invalidate];
        [self.sendBtn setTitle:[NSString stringWithFormat:@"发送验证码"] forState:UIControlStateNormal];
    }
    
//    NSLog(@"--------");
    
    
    
}

- (void)createCommbox:(NSString*)placeholder _rect:(CGRect)_rect maxLength:(int)maxLength control:(RootViewController*)control view:(UIView*)view callback:(ResponseCallback)callback text:(NSString*)text panelFrame:(CGRect)panelFrame isInput:(BOOL)isInput align:(NSTextAlignment)align
{
    self.commboxControl = control;
    self.commboxParent = view;
    self.commboxBack = callback;
    self.commboxPanelFrame = panelFrame;
    int text_x = _rect.origin.x, text_w = _rect.size.width - _rect.size.height;
    self.commbox = [[UITextField alloc] initWithFrame:CGRectMake(text_x, _rect.origin.y, text_w, _rect.size.height)];
    self.commbox.font = FONT(14);
    self.commbox.placeholder = placeholder;
    self.commbox.clearButtonMode = UITextFieldViewModeWhileEditing;
    self.commbox.textAlignment = align;
    self.commbox.tag = maxLength;
    self.commbox.delegate = self.commboxControl;
    [self.commboxParent addSubview:self.commbox];
    self.commbox.text = text;
    
    int btn_size = self.commbox.frame.size.height, btn_x = CGRectGetMaxX(self.commbox.frame);
    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(btn_x, _rect.origin.y, btn_size, btn_size)];
    [button addTarget:self action:@selector(doCommboxClick:) forControlEvents:UIControlEventTouchUpInside];
    [button setBackgroundImage:[UIImage imageNamed:@"top_def1"] forState:UIControlStateHighlighted];
    [view addSubview:button];

    int icon_w = btn_size * 0.4, icon_h = icon_w * 0.63, icon_x = (btn_size - icon_w) / 2, icon_y = (btn_size - icon_h) / 2;
    self.commboxIcon = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"arrow_bottom.png"]];
    self.commboxIcon.frame = CGRectMake(icon_x, icon_y, icon_w, icon_h);
    [button addSubview:self.commboxIcon];
    
    if (!isInput) {
        self.commbox.userInteractionEnabled = NO;
        UIButton *btn = [[UIButton alloc] initWithFrame:_rect];
        btn.backgroundColor = [UIColor clearColor];
        [btn addTarget:self action:@selector(doCommboxClick:) forControlEvents:UIControlEventTouchUpInside];
        [self.commboxParent addSubview:btn];
    }
    
    self.commboxCoverView = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, WindowWidth, WindowHeight)];
    [self.commboxCoverView addTarget:self action:@selector(removeCommboxCoverView:) forControlEvents:UIControlEventTouchUpInside];
    self.commboxCoverView.alpha = 0.5;
    self.commboxCoverView.backgroundColor = [UIColor blackColor];
    self.commboxCoverView.hidden = YES;
    self.commboxTimer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(addCommboxCover) userInfo:nil repeats:NO];
    
    
}
//组合框的点击事件
- (void)doCommboxClick:(UIButton *)btn
{
    if (self.commboxArray == nil || self.commboxArray.count == 0) {
        return;
    }
    float item_h = self.commbox.frame.size.height, max_view_h = self.commboxPanelFrame.size.height;
    int view_height = item_h * ((int) self.commboxArray.count), view_h = (view_height > max_view_h ? max_view_h : view_height);
    self.commboxItemView = [[UIScrollView alloc] initWithFrame:CGRectMake(self.commboxPanelFrame.origin.x, self.commboxPanelFrame.origin.y, self.commboxPanelFrame.size.width, 0)];
    self.commboxItemView.backgroundColor = [UIColor whiteColor];//遮盖的颜色
    self.commboxItemView.contentSize = CGSizeMake(0, view_height);
    self.commboxItemView.bounces = NO;
    self.commboxItemView.layer.borderWidth = 0.5;
    self.commboxItemView.layer.borderColor = [[UIColor blackColor] CGColor];//边界颜色
    [self.commboxControl.view addSubview:self.commboxItemView];
    for (int i = 0; i < self.commboxArray.count; i++) {
        UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0.5, i * item_h, self.commboxItemView.frame.size.width - 1, item_h)];
        [button setTitle:self.commboxArray[i] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(doCommboxItemClick:) forControlEvents:UIControlEventTouchUpInside];
        
        UIColor *color = ([self.commbox.text isEqualToString:self.commboxArray[i]] ? [UIColor redColor] : [UIColor blackColor]);//选中某一行的颜色
        
        [button setTitleColor:color forState:UIControlStateNormal];
        [button setBackgroundImage:[UIImage imageNamed:@"top_def1"] forState:UIControlStateHighlighted];
        button.titleLabel.font = FONT(14);
        button.tag = i;
        
        [self.commboxItemView addSubview:button];
        if (i != self.commboxArray.count - 1) {
//        [ToolUtil createLine:i * item_h superView:self.commboxItemView lift:0 width:WindowWidth / 2];
            UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0.5, i * item_h, self.commboxItemView.frame.size.width - 0.5, 0.5)];
            line.backgroundColor = [UIColor grayColor];
            [self.commboxItemView addSubview:line];
        
        }
    }
    
    [[self.commboxParent superview] endEditing:YES];
    self.commboxCoverView.hidden = NO;
    self.commboxIcon.image = [UIImage imageNamed:@"arrow_up.png"];
    [UIView animateWithDuration:0.2 animations:^{
        CGRect frame = self.commboxItemView.frame;
        self.commboxItemView.frame = CGRectMake(frame.origin.x, frame.origin.y, frame.size.width, view_h);
    }];

    
}
- (void)addCommboxCover {
    [self.commboxTimer invalidate];
    _commboxTimer = nil;
    [self.commboxControl.view addSubview:self.commboxCoverView];
}
// 组合框选项的点击事件
- (void)doCommboxItemClick:(UIButton*)btn {
    [self removeCommboxCoverView:btn];
    self.commbox.text = self.commboxArray[btn.tag];
//    NSLog(@"2%@",self.commbox.text);
//    NSLog(@"%@",self.commboxArray[btn.tag]);
    if (nil != self.commboxBack) {
        self.commboxBack([NSMutableDictionary dictionaryWithDictionary:@{@"text" : self.commbox.text, @"index" : [NSNumber numberWithInteger:btn.tag]}]);
    }
}
// 组合框遮盖层的点击事件
- (void)removeCommboxCoverView:(UIButton*)btn {
    self.commboxCoverView.hidden = YES;
    self.commboxIcon.image = [UIImage imageNamed:@"arrow_bottom.png"];
    [UIView animateWithDuration:0.2 animations:^{
        CGRect frame = self.commboxItemView.frame;
        self.commboxItemView.frame = CGRectMake(frame.origin.x, frame.origin.y, frame.size.width, 0);
    } completion:^(BOOL finished) {
        [self.commboxItemView removeFromSuperview];
    }];
}


#pragma mark 获得字符串的字节长度
+ (int)getStrLen:(NSString*)text {
    if ([ToolUtil isBlank:text]) {
        return 0;
    }
    int length = 0;
    for (int i = 0; i < text.length; i++) {
        int ascii = [[text substringWithRange:NSMakeRange(i, 1)] characterAtIndex:0];
        if (ascii >= 0 && ascii <= 255) {
            length++;
        } else {
            length += 2;
        }
    }
    return length;
}
//+ (void) creatAlertView:(NSArray *)array control:(UIViewController *)control callback:(ResponseCallback)callback
//{
//    UIAlertController * alertController = [UIAlertController alertControllerWithTitle:@"" message:@"" preferredStyle:(UIAlertControllerStyleActionSheet)];
////    UIAlertAction * action = [ui]
//    UIAlertAction * CameraAction = [UIAlertAction actionWithTitle:@"相机" style:(UIAlertActionStyleDefault) handler:callback];
//    UIAlertAction * AlbumAction = [UIAlertAction actionWithTitle:@"相册" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
//        UIImagePickerControllerSourceType sourceType2 = UIImagePickerControllerSourceTypePhotoLibrary;
//        
//    }];
//    UIAlertAction * cancelAction = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) {
//        NSLog(@"h");
//        
//    }];
//    [alertController addAction:CameraAction];
//    [alertController addAction:AlbumAction];
//    [alertController addAction:cancelAction];
//    
//    [control presentViewController:alertController animated:YES completion:nil];
//
//}

+ (void)callPhone:(RootViewController*)control phone:(NSString*)phone {
    [ToolUtil showOther:control type:@"tel" value:phone];
}

+ (void)showOther:(RootViewController*)control type:(NSString*)type value:(NSString*)value {
    if ([ToolUtil isBlank:type] || [ToolUtil isBlank:value]) {
        return;
    }
    
    UIWebView *callWebview = [[UIWebView alloc] init];
    callWebview.backgroundColor = [UIColor yellowColor];
    NSString *telUrl = [NSString stringWithFormat:@"%@:%@", type, value];
    [callWebview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:telUrl]]];
    [control.view addSubview:callWebview];
   
}

+ (float)createLine:(float)y superView:(UIView*)view lift:(float)lift width:(float)width hight:(float)hight color:(UIColor *)color
{
    UIView *line = [[UIView alloc] initWithFrame:CGRectMake(lift, y, width, hight)];
    line.backgroundColor = color;
    [view addSubview:line];
    return CGRectGetMaxY(line.frame);
}
+ (float)createVerticalLine:(float)y superView:(UIView*)view lift:(float)lift height:(float)height
{
    UIView *line = [[UIView alloc] initWithFrame:CGRectMake(lift, y, 0.5, height)];
    line.backgroundColor = [UIColor grayColor];
    [view addSubview:line];
    return CGRectGetMaxY(line.frame);

}
//- (void)prompt:(NSString*)msg view:(UIView *)aView{
//    view = aView;
//    [aView endEditing:YES];
//    if (nil != promptTimer) {
//        [promptTimer invalidate];
//        promptTimer = nil;
//    }
//    UILabel *label = (UILabel*) [aView viewWithTag:300];
//    msg = ([ToolUtil isBlank:msg] ? @"" : msg);
//    if (nil == label) {
//        label = [[UILabel alloc] init];
//        [view addSubview:label];
//        label.backgroundColor = [UIColor blackColor];
//        label.textColor = [UIColor whiteColor];
//        label.textAlignment = NSTextAlignmentCenter;
//        label.font = FONT(14);
//        label.alpha = 0.6;
//        [label.layer setCornerRadius:margin_3];
//        [label.layer setMasksToBounds:YES];
//        label.tag = 300;
//        label.numberOfLines = 0;
//    }
////    CGSize size = [ToolUtil autoWidth1:msg width:WindowWidth - title_height height:MAXFLOAT num:14];
//    CGSize size = [msg sizeWithFont:label.font constrainedToSize:CGSizeMake(WindowWidth - title_height, MAXFLOAT)];
//    int width = size.width + title_height / 2, height = size.height + title_height / 4;
//    width = (width < title_height * 2 ? title_height * 2 : width);
//    int x = (WindowWidth - width) / 2, y = WindowHeight - height - bottom_height - margin_5;
//    CGRect tempFrame = label.frame;
//    tempFrame = CGRectMake(x, y, width, height);
//    label.frame = tempFrame;
//    label.text = msg;
//    label.hidden = NO;
//    promptTimer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(clearPromptTimer) userInfo:nil repeats:NO];
//    
//}
//- (void)clearPromptTimer {
//    UILabel *label = (UILabel*) [view viewWithTag:300];
//    label.hidden = YES;
//    [promptTimer invalidate];
//    promptTimer = nil;
//}

//分享
+ (void)share:(NSString*)title content:(NSString*)content url:(NSString*)url image:(id)image view:(UIView*)view control:(RootViewController*)control
{
    if ([self isBlank:title] || image == nil || [self isBlank:url] ) {
        [control prompt:@"参数不全, 分享失败"];
        return;
    }
    NSString * imgPath = @"";
    if ([image isKindOfClass:[NSString class]]) {
        imgPath = image;
    }else if ([image isKindOfClass:[NSData class]]){
        imgPath = [FileUtil documentPath:@"share.png"];
//        [image writeToFile:imgPath atomically:NO encoding:NSUTF8StringEncoding error:nil];
        [((NSData *)image) writeToFile:imgPath atomically:YES];
    }else if ([image isKindOfClass:[UIImage class]]){
        imgPath = [FileUtil documentPath:@"share.png"];
        [UIImagePNGRepresentation((UIImage*)image) writeToFile:imgPath atomically:YES];
    }
    
    //构造分享内容
    id<ISSContent> publishContent = [ShareSDK content:content
                                       defaultContent:@""
                                                image:[ShareSDK imageWithPath:imgPath]
                                                title:title
                                                  url:url description:@""
                                            mediaType:SSPublishContentMediaTypeNews];
    //创建弹出菜单容器
    id<ISSContainer> container = [ShareSDK container];
    [container setIPadContainerWithView:view arrowDirect:UIPopoverArrowDirectionUp];
    
    //弹出分享菜单
    [ShareSDK showShareActionSheet:container
                         shareList:nil
                           content:publishContent
                     statusBarTips:YES
                       authOptions:nil
                      shareOptions:nil
                            result:^(ShareType type, SSResponseState state, id<ISSPlatformShareInfo> statusInfo, id<ICMErrorInfo> error, BOOL end) {
                                if (state == SSResponseStateSuccess) {
                                    [control prompt:@"分享成功"];
                                }else if (state == SSResponseStateFail){
                                    [control prompt:[error errorDescription]];
                                }
        
    }];
    
}

//自适应高度
+ (CGFloat)customAutoHeigh:(NSString *)contentString width:(CGFloat)width num:(CGFloat)num
{
    CGRect rect = [contentString boundingRectWithSize:CGSizeMake(width, 0) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:FONT(num)} context:nil];
    return rect.size.height;
}
//自适应宽度
+ (CGFloat)autoWidth:(NSString *)nameString width:(CGFloat)width height:(CGFloat)height num:(CGFloat)num
{
    CGSize size = CGSizeMake(width, height);
//    CGSize labelSize = [nameString sizeWithFont:FONT(num) constrainedToSize:size lineBreakMode:NSLineBreakByWordWrapping];
    CGRect  labelSize = [nameString boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:FONT(num)} context:nil];
    return labelSize.size.width;
    
}
+ (CGSize)autoWidth1:(NSString *)nameString width:(CGFloat)width height:(CGFloat)height num:(CGFloat)num
{
    CGSize size = CGSizeMake(width, height);
    //    CGSize labelSize = [nameString sizeWithFont:FONT(num) constrainedToSize:size lineBreakMode:NSLineBreakByWordWrapping];
    CGRect  labelSize = [nameString boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:FONT(num)} context:nil];
    return labelSize.size;
}

@end
